<html>
  <head>
    <script type="text/javascript" src="log.json"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">

      google.load('visualization', '1.0', {'packages':['corechart']});

      google.setOnLoadCallback(drawChart);

      var log = {
        'start': log[0].start,
        'end': log[log.length - 1].end,
        'children': log
      };

      function drawChartFor(log) {
        var rows = [];
        if (log.children.start != log.start) {
          rows.push(['Rest of action execution', log.start, '']);
        }
        var lastTimestamp = log.start;
        for (var i = 0; i < log.children.length; ++i) {
          var timeTaken = (log.children[i].end - log.children[i].start);
          lastTimestamp += timeTaken
          rows.push([log.children[i].command + ':' + log.children[i].event,
              lastTimestamp, log.children[i].command + ': ' + timeTaken]);
        }
        if (log.end != lastTimestamp) {
          rows.push(['Rest of action execution', log.end, '']);
        }

        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Time');
        data.addColumn('number', 'Cumulative time');
        data.addColumn({type: 'string', role: 'tooltip'});
        data.addRows(rows);

        var chart = new google.visualization.SteppedAreaChart(document.getElementById('chart_div'));
	chart.draw(data, {width: 1200, height: 400, legend: 'top', vaxis: {minValue: log.start}});

        google.visualization.events.addListener(
            chart, 'select', function() { zoomIfPossible(chart, log.children) });
      }


      function drawChart() {
        drawChartFor(log);
      }

      function hasSameStartAndEndTime(entry1, entry2) {
	return entry1.start == entry2.start &&
	  entry1.end == entry2.end;
      }

      function zoomIfPossible(chart, children) {
	if (log.children != children) {
	  console.log('Don\'t know how to zoom further than that');
	  return;
	}

        var selection = chart.getSelection();
        if (!selection || selection.length != 1) {
          return;
        }
        var point = selection[0];
        var row = point.row;
        if (!row) {
          return;
	}
	if (log.children.length > row) {
	  return;
	}
	entry = log.children[row - 1];
	console.log(entry);
        if (!entry.children || !entry.children.length || hasSameStartAndEndTime(entry, entry.children[0])) {
          console.log('No further breakdown of action');
          return;
        }
        drawChartFor(entry);
      }
    </script>
  </head>

  <body>
    <div id="chart_div"></div>
  </body>
</html>
